package com.chhuang.ewcrm.ctrl;

import com.browniebytes.javafx.control.DateTimePicker;
import com.chhuang.ewcrm.App;
import com.chhuang.ewcrm.api.AppRequest;
import com.chhuang.ewcrm.api.ServiceRxSchedulers;
import com.chhuang.ewcrm.api.ServiceSubscriber;
import com.chhuang.ewcrm.application.LPKeyBoardApp;
import com.chhuang.ewcrm.bean.DeliveryBean;
import com.chhuang.ewcrm.bean.WeighTypeBean;
import com.chhuang.ewcrm.cons.Constants;
import com.chhuang.ewcrm.dao.WCustomerDao;
import com.chhuang.ewcrm.dao.WLicensePlateDao;
import com.chhuang.ewcrm.dao.WWeighTempDao;
import com.chhuang.ewcrm.date.DateUtil;
import com.chhuang.ewcrm.entity.*;
import com.chhuang.ewcrm.string.StringUtil;
import com.chhuang.ewcrm.thread.PrintWeighRecordThread;
import com.chhuang.ewcrm.utils.*;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXToggleButton;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;

import static javafx.application.Platform.runLater;

/**
 * 手工补单
 */
public class AddWeighController implements InitController{
    private final Logger logger = LoggerFactory.getLogger(AddWeighController.class);

    @FXML
    private ComboBox<WLicensePlate> lprComboBox;
    @FXML
    private JFXButton lpKeyBoardJFXButton;
    private StringProperty lptext = new SimpleStringProperty();//车牌字符串
    @FXML
    private ComboBox<WeighTypeBean> weighTypeComboBox;
    @FXML
    private ComboBox<EWarehouse> warehouseComboBox;
    @FXML
    private FlowPane warehouse1FlowPane;
    @FXML
    private ComboBox<EWarehouse> warehouse1ComboBox;
    @FXML
    private FlowPane customerFlowPane;
    @FXML
    private ComboBox<WCustomer> customerComboBox;
    @FXML
    private ComboBox<EGoods> goodsComboBox;
    @FXML
    private FlowPane goods1FlowPane;
    @FXML
    private ComboBox<EGoods> goods1ComboBox;
    @FXML
    private FlowPane salesmanFlowPane;
    @FXML
    private ComboBox<SysUser> salesmanComboBox;
    @FXML
    private ComboBox<SysUser> chargemanComboBox;
    @FXML
    private TextField grossWeightTextField;
    @FXML
    private TextField tareWeightTextField;
    @FXML
    private TextField impurityWeightTextField;
    @FXML
    private TextField netWeightTextField;
    @FXML
    private TextField priceTextField;
    @FXML
    private TextField amountTextField;
    @FXML
    private TextField remarkTextField;
    @FXML
    private DateTimePicker enterTimeDateTimePicker;
    private ObjectProperty<LocalDateTime> enterTimeDateTime;
    @FXML
    private DateTimePicker outTimeDateTimePicker;
    private ObjectProperty<LocalDateTime> outTimeDateTime;
    @FXML
    private JFXButton saveJFXButton;

    @FXML
    private FlowPane priceFlowPane;
    @FXML
    private FlowPane deductionMoneyFlowPane;
    @FXML
    private FlowPane amountFlowPane;
    @FXML
    private FlowPane isDeliveryFlowPane;
    @FXML
    private ComboBox<DeliveryBean> isDeliveryComboBox;
    @FXML
    private TextField deductionMoneyTextField;
    @FXML
    private Label amountLabel;
    @FXML
    private JFXToggleButton isPrintJFXToggleButton;

    private final NumberTextFilter numberTextFilter = new NumberTextFilter();
    private final WLicensePlateDao wLicensePlateDao = App.getSession().getMapper(WLicensePlateDao.class);
    private final WCustomerDao wCustomerDao = App.getSession().getMapper(WCustomerDao.class);
    private final WWeighTempDao wWeighTempDao = App.getSession().getMapper(WWeighTempDao.class);

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        //初始化过磅类别
        initWeighType();
        //初始化车牌
        initLp();
        //初始化仓库
        initWarehouse();
        //初始化客户
        initCustomer();
        //初始化商品
        initGoods();
        //初始化业务员和负责人
        initMan();
        //是否是自提
        initIsDelivery();
        //初始化毛皮扣重
        initWeigh();
        //初始化价格扣款总价
        initPrice();
        //初始化日期控件
        initDateTimePicker();
        //初始化打印开关
        initIsPrintJFXToggleButton();
        //初始化按钮监听
        initButton();
    }

    private void initIsPrintJFXToggleButton() {
        isPrintJFXToggleButton.setOnAction(event -> {
            if(isPrintJFXToggleButton.isSelected()){
                isPrintJFXToggleButton.setText("需要打印磅单");
            }else {
                isPrintJFXToggleButton.setText("不需要打印磅单");
            }
        });
    }

    /**
     * 是否是自提
     */
    private void initIsDelivery() {
        List<DeliveryBean> list = new LinkedList<>();
        list.add(new DeliveryBean(false, "否"));//0
        list.add(new DeliveryBean(true, "是"));//1
        isDeliveryComboBox.getItems().addAll(list);
        isDeliveryComboBox.setConverter(new StringConverter<>() {
            @Override
            public String toString(DeliveryBean deliveryBean) {
                return deliveryBean==null?null:deliveryBean.getTitle();
            }

            @Override
            public DeliveryBean fromString(String s) {
                return null;
            }
        });
        isDeliveryComboBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue)->{
            WeighTypeBean weighTypeBean = weighTypeComboBox.getSelectionModel().getSelectedItem();
            if(weighTypeBean!=null)weighTypeAndIsDelivery(newValue.isDelivery(), weighTypeBean.getWeighTypeId());
        });
        isDeliveryComboBox.getSelectionModel().select(0);//默认选中第一项
    }

    /**
     * 过磅类别与是否自提联动
     * @param delivery
     * @param weighTypeId
     */
    private void weighTypeAndIsDelivery(boolean delivery, int weighTypeId){
        if(delivery){//是自提
            switch (weighTypeId){//入库自提的不需要填写金额
                case 0://入库
                    priceFlowPane.setVisible(false); priceFlowPane.setManaged(false);
                    deductionMoneyFlowPane.setVisible(false); deductionMoneyFlowPane.setManaged(false);
                    amountFlowPane.setVisible(false); amountFlowPane.setManaged(false);
                    break;
                default://其它
                    priceFlowPane.setVisible(true); priceFlowPane.setManaged(true);
                    deductionMoneyFlowPane.setVisible(true); deductionMoneyFlowPane.setManaged(true);
                    amountFlowPane.setVisible(true); amountFlowPane.setManaged(true);
                    break;
            }
        }else {
            switch (weighTypeId){//出库不是自提的不需要填写金额
                case 1://出库
                    priceFlowPane.setVisible(false); priceFlowPane.setManaged(false);
                    deductionMoneyFlowPane.setVisible(false); deductionMoneyFlowPane.setManaged(false);
                    amountFlowPane.setVisible(false); amountFlowPane.setManaged(false);
                    break;
                default://其它
                    priceFlowPane.setVisible(true); priceFlowPane.setManaged(true);
                    deductionMoneyFlowPane.setVisible(true); deductionMoneyFlowPane.setManaged(true);
                    amountFlowPane.setVisible(true); amountFlowPane.setManaged(true);
                    break;
            }
        }
    }

    /**
     * 初始化车牌
     */
    private void initLp() {
        List<WLicensePlate> wLicensePlateList = wLicensePlateDao.query(null);
        if(wLicensePlateList!=null && !wLicensePlateList.isEmpty()){
            lprComboBox.getItems().addAll(wLicensePlateList);
            new AutoCompleteComboBoxListener<>(lprComboBox);
        }
        //只能输入大写
        lprComboBox.getEditor().setTextFormatter(new TextFormatter<>(new UpCastTextFilter()));

        lprComboBox.setConverter(new StringConverter<>() {
            //把对象，设置显示值
            @Override
            public String toString(WLicensePlate wLicensePlate) {
                return wLicensePlate!=null?wLicensePlate.getWlpNumber():null;
            }

            //添加新值时，转对象
            @Override
            public WLicensePlate fromString(String s) {
                WLicensePlate wLicensePlate = null;
                if(StringUtils.isNotEmpty(s)){
                    wLicensePlate = new WLicensePlate();
                    wLicensePlate.setWlpNumber(s.toUpperCase());
                    List<WLicensePlate> wLicensePlates = wLicensePlateDao.query(wLicensePlate);
                    if(wLicensePlate!=null && !wLicensePlates.isEmpty()){
                        wLicensePlate = wLicensePlates.get(0);
                    }else {
                        wLicensePlate.setCreateTime(new Date());
                        wLicensePlateDao.insert(wLicensePlate);
                        lprComboBox.getItems().add(wLicensePlate);
                    }
                }
                return wLicensePlate;
            }
        });

        //弹出键盘输入车牌
        lpKeyBoardJFXButton.setOnAction(event -> new LPKeyBoardApp(lptext).start(new Stage()));
        //监听 车牌字符串 修改
        lptext.addListener((observableValue, s, t1) -> {
            if(StringUtils.isNotEmpty(t1)) {
                WLicensePlate wLicensePlate = new WLicensePlate();
                wLicensePlate.setWlpNumber(t1);
                lprComboBox.getSelectionModel().select(lprComboBox.getConverter().fromString(wLicensePlate.getWlpNumber()));
            }
        });
    }

    /**
     * 初始化业务员和负责人
     */
    private void initMan() {
        SysUser voidUser = new SysUser();
        voidUser.setUsername("--请选择--");

        StringConverter<SysUser> converter = new StringConverter<>() {
            @Override
            public String toString(SysUser sysUser) {
                return sysUser==null?null:(sysUser.getFullname()==null?sysUser.getUsername():sysUser.getFullname());
            }

            @Override
            public SysUser fromString(String s) {
                return null;
            }
        };

        chargemanComboBox.setConverter(converter);
        chargemanComboBox.getItems().add(voidUser);
        AppRequest.getInstance().getService().getChargerMans()
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取负责人请求") {
                    @Override
                    protected void onHandleSuccess(List<SysUser> users) {
                        if(users!=null && !users.isEmpty()) {
                            runLater(()->
                                    chargemanComboBox.getItems().addAll(users)
                            );
                        }
                    }
                });
        chargemanComboBox.getSelectionModel().select(0);

        salesmanComboBox.setConverter(converter);
        salesmanComboBox.getItems().add(voidUser);
        AppRequest.getInstance().getService().getSalesmans()
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取业务员请求") {
                    @Override
                    protected void onHandleSuccess(List<SysUser> users) {
                        if(users!=null && !users.isEmpty()) {
                            runLater(()->
                                salesmanComboBox.getItems().addAll(users)
                            );
                        }
                    }
                });
        salesmanComboBox.getSelectionModel().select(0);
    }

    /**
     * 初始化商品
     */
    private void initGoods() {
        StringConverter<EGoods> converter = new StringConverter<>() {
            @Override
            public String toString(EGoods eGoods) {
                return eGoods==null?null:eGoods.getGoodsName();
            }

            @Override
            public EGoods fromString(String s) {
                return null;
            }
        };

        goodsComboBox.setConverter(converter);

        goods1ComboBox.setConverter(converter);
    }

    /**
     * 初始化客户
     */
    private void initCustomer() {
        List<WCustomer> wCustomerList = wCustomerDao.query(null);
        if(wCustomerList!=null && !wCustomerList.isEmpty()){
            customerComboBox.getItems().addAll(wCustomerList);
            new AutoCompleteComboBoxListener<>(customerComboBox);//自动完成功能
        }

        customerComboBox.getEditor().setTextFormatter(new TextFormatter<>(new LengthTextFilter(127)));
        customerComboBox.setConverter(new StringConverter<>() {
            @Override
            public String toString(WCustomer wCustomer) {
                return wCustomer==null?null:wCustomer.getCustomerName();
            }

            @Override
            public WCustomer fromString(String s) {
                WCustomer wCustomer = null;
                if(StringUtils.isNotEmpty(s)){
                    wCustomer = new WCustomer();
                    wCustomer.setCustomerName(s);
                    List<WCustomer> wCustomers = wCustomerDao.query(wCustomer);
                    if(wCustomers!=null && !wCustomers.isEmpty()){
                        wCustomer = wCustomers.get(0);
                    }else {
                        Date now = new Date();
                        wCustomer.setModifyTime(now);
                        wCustomer.setCreateTime(now);
                        wCustomerDao.insert(wCustomer);
                        customerComboBox.getItems().add(wCustomer);
                    }
                }
                return wCustomer;
            }
        });
    }

    /**
     * 初始化仓库
     */
    private void initWarehouse() {
//        EWarehouse warehouseTemp = new EWarehouse();
//        warehouseTemp.setWarehouseName("--请选择--");
//        warehouseComboBox.getItems().add(warehouseTemp);
//        warehouse1ComboBox.getItems().add(warehouseTemp);

        AppRequest.getInstance().getService().getWarehouses()
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取所有仓库请求") {
                    @Override
                    protected void onHandleSuccess(List<EWarehouse> warehouses) {
                        if(warehouses!=null && !warehouses.isEmpty()) {
                            runLater(()->{
                                warehouse1ComboBox.getItems().addAll(warehouses);
                                warehouseComboBox.getItems().addAll(warehouses);

                                warehouseComboBox.getSelectionModel().select(0);
                                warehouse1ComboBox.getSelectionModel().select(0);
                            });
                        }
                    }
                });

        StringConverter<EWarehouse> converter = new StringConverter<>() {
            @Override
            public String toString(EWarehouse eWarehouse) {
                return eWarehouse==null?null:eWarehouse.getWarehouseName();
            }

            @Override
            public EWarehouse fromString(String s) {
                return null;
            }
        };

        warehouseComboBox.setConverter(converter);
        warehouse1ComboBox.setConverter(converter);

        warehouseComboBox.getSelectionModel().selectedItemProperty().addListener((observableValue, oldValue, newValue) -> {
            WeighTypeBean weighTypeBean = weighTypeComboBox.getSelectionModel().getSelectedItem();
            //修改物品
            getEGoods(weighTypeBean.getWeighTypeId(), newValue==null?null:newValue.getWarehouseId());
        });

        warehouse1ComboBox.getSelectionModel().selectedItemProperty().addListener((observableValue, oldValue, newValue) -> {
            //修改原物品
            getEGoods1(newValue==null?null:newValue.getWarehouseId());
        });

//        warehouseComboBox.getSelectionModel().select(0);
//        warehouse1ComboBox.getSelectionModel().select(0);
    }

    private void getEGoods(int weightTypeId, String warehouseId){
        int typeId = 0;
        switch (weightTypeId){
            case 0,2:typeId=0;break;
            case 1:typeId=1;break;
            case 3:typeId=2;break;
        }
        //修改物品
        AppRequest.getInstance().getService().getGoods(typeId, warehouseId)
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取物品名称请求") {
                    @Override
                    protected void onHandleSuccess(List<EGoods> goodsList) {
                        runLater(()->{
                            goodsComboBox.getItems().clear();
                            if(goodsList!=null && !goodsList.isEmpty()) {
                                goodsComboBox.getItems().addAll(goodsList);
                                goodsComboBox.getSelectionModel().select(0);
                            }
                        });
                    }
                });
        goodsComboBox.getSelectionModel().select(0);
    }

    private void getEGoods1(String warehouseId1){
        //修改原物品
        AppRequest.getInstance().getService().getGoods(1, warehouseId1)
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取原物品名称请求") {
                    @Override
                    protected void onHandleSuccess(List<EGoods> goodsList) {
                        runLater(()-> {
                            goods1ComboBox.getItems().clear();
                            if (goodsList != null && !goodsList.isEmpty()) {
                                goods1ComboBox.getItems().addAll(goodsList);
                                goods1ComboBox.getSelectionModel().select(0);
                            }
                        });
                    }
                });
        goods1ComboBox.getSelectionModel().select(0);
    }

    /**
     * 初始化重量输入框
     */
    private void initWeigh(){
        //毛重
        grossWeightTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
        grossWeightTextField.textProperty().addListener((observable, oldValue, newValue)->{
            autoWeigh();
        });
        //皮重
        tareWeightTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
        tareWeightTextField.textProperty().addListener((observable, oldValue, newValue)->{
            autoWeigh();
        });
        //设置扣重只接收数字输入
        impurityWeightTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
        //修改扣重时
        impurityWeightTextField.focusedProperty().addListener((observable, oldValue, newValue)->{
            if(!newValue) {
                autoWeigh();
            }
        });
        //净重
        netWeightTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
        netWeightTextField.textProperty().addListener((observable, oldValue, newValue)->{
            autoMoney();
        });
    }

    /**
     * 初始化价格 扣款 总金额
     */
    private void initPrice() {
        //设置价格只接收数字
        priceTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
        //修改价格时
        priceTextField.focusedProperty().addListener((observable, oldValue, newValue)->{
            if(!newValue) {
                autoMoney();
            }
        });

        //设置价格只接收数字
        deductionMoneyTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
        deductionMoneyTextField.focusedProperty().addListener((observableValue, aBoolean, t1) -> {
            if(!t1){
                autoMoney();
            }
        });

        //设置总价只接收数字
        amountTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
    }

    /**
     * 联动重量 当毛重，皮重， 扣重 修改后 调用
     */
    private void autoWeigh(){
        String tareWeightStr = tareWeightTextField.getText();
        String grossWeightStr = grossWeightTextField.getText();
        if(StringUtils.isNotEmpty(tareWeightStr) && StringUtil.isPositiveNumber(tareWeightStr) &&
                StringUtils.isNotEmpty(grossWeightStr) && StringUtil.isPositiveNumber(grossWeightStr)){
            double tareWeight = Double.parseDouble(tareWeightStr);
            double grossWeight = Double.parseDouble(grossWeightStr);

            //扣重
            double impurityWeight = 0;
            String impurityWeightStr = impurityWeightTextField.getText();
            if(StringUtils.isNotEmpty(impurityWeightStr) && StringUtil.isPositiveNumber(impurityWeightStr))
                impurityWeight = Double.parseDouble(impurityWeightStr);

            //净重
            double netWeight = grossWeight-tareWeight-impurityWeight;
            netWeightTextField.setText(String.format("%.3f",netWeight));
        }
    }

    /**
     * 联动金额  当净重，价格 扣款 修改后 调用
     */
    private void autoMoney(){
        String netWeightStr = netWeightTextField.getText();
        WeighTypeBean weighTypeBean = weighTypeComboBox.getValue();
        if(StringUtils.isNotEmpty(netWeightStr) && StringUtil.isPositiveNumber(netWeightStr) &&
                weighTypeBean.getWeighTypeId()!=3){//其它过磅不需要联动
            double netWeight = Double.parseDouble(netWeightStr);
            //扣款
            double deductionMoney = 0;
            String deductionMoneyStr = deductionMoneyTextField.getText();
            if(StringUtils.isNotEmpty(deductionMoneyStr) && StringUtil.isPositiveNumber(deductionMoneyStr))
                deductionMoney = Double.parseDouble(deductionMoneyStr);

            //价格存在 计算总价
            double price =0;
            String priceStr = priceTextField.getText();
            if(StringUtils.isNotEmpty(priceStr) && StringUtil.isPositiveNumber(priceStr))
                price = Double.parseDouble(priceStr);
            amountTextField.setText(String.format("%.2f",netWeight*price-deductionMoney));
        }
    }

    /**
     * 初始化过磅类别
     */
    private void initWeighType() {
        //过磅类别
        weighTypeComboBox.getItems().addAll(Constants.WEIGH_TYPES);
        weighTypeComboBox.setConverter(new StringConverter<>() {
            //把对象，设置显示值
            @Override
            public String toString(WeighTypeBean weighTypeBean) {
                return weighTypeBean==null?null:weighTypeBean.getWeighTypeName();
            }
            //添加新值时，转对象
            @Override
            public WeighTypeBean fromString(String s) {return null;}
        });
        weighTypeComboBox.getSelectionModel().selectedItemProperty().addListener(
                (ObservableValue<? extends WeighTypeBean> observableValue, WeighTypeBean oldWtb, WeighTypeBean newWtb)-> {
                    DeliveryBean delivery = isDeliveryComboBox.getSelectionModel().getSelectedItem();
                    if(delivery!=null)weighTypeAndIsDelivery(delivery.isDelivery(), newWtb.getWeighTypeId());

                    if(newWtb.getWeighTypeId()<2){//入库 或 出库
                        salesmanFlowPane.setVisible(true); salesmanFlowPane.setManaged(true);
                        isDeliveryFlowPane.setVisible(true);isDeliveryFlowPane.setManaged(true);
                        isDeliveryComboBox.getSelectionModel().select(newWtb.getWeighTypeId());
                    }else {
                        salesmanFlowPane.setVisible(false); salesmanFlowPane.setManaged(false);
                        isDeliveryFlowPane.setVisible(false);isDeliveryFlowPane.setManaged(false);
                    }

                    if(newWtb.getWeighTypeId()==2){//内部周转
                        warehouse1FlowPane.setVisible(true); warehouse1FlowPane.setManaged(true);
                        customerFlowPane.setVisible(false); customerFlowPane.setManaged(false);
                        goods1FlowPane.setVisible(true); goods1FlowPane.setManaged(true);
                    }else {
                        warehouse1FlowPane.setVisible(false);  warehouse1FlowPane.setManaged(false);
                        customerFlowPane.setVisible(true); customerFlowPane.setManaged(true);
                        goods1FlowPane.setVisible(false); goods1FlowPane.setManaged(false);
                    }

                    if(newWtb.getWeighTypeId()==3){//其它过磅
                        priceFlowPane.setVisible(false); priceFlowPane.setManaged(false);
                        deductionMoneyFlowPane.setVisible(false); deductionMoneyFlowPane.setManaged(false);
                        amountLabel.setText("过磅费：");amountTextField.setEditable(true);
                        amountTextField.setStyle("");
                    }else {
                        amountLabel.setText("总 价 ：");amountTextField.setEditable(false);
                        amountTextField.setStyle("-fx-background-color: gainsboro;");
                    }

                    //修改物品
                    EWarehouse warehouse = warehouseComboBox.getValue();
                    getEGoods(newWtb.getWeighTypeId(), warehouse==null?null:warehouse.getWarehouseId());
                }
        );
        weighTypeComboBox.getSelectionModel().select(0);//默认选中第一项
    }

    /**
     * 初始化日期控件
     */
    private void initDateTimePicker(){
        enterTimeDateTimePicker.setPopupPreWidth(enterTimeDateTimePicker.getPrefWidth());//设置下拉选择框宽度和日期输入框一样
        outTimeDateTimePicker.setPopupPreWidth(outTimeDateTimePicker.getPrefWidth());
        enterTimeDateTime = enterTimeDateTimePicker.dateTimeProperty();
        outTimeDateTime = outTimeDateTimePicker.dateTimeProperty();
    }

    /**
     * 初始化按钮监听
     */
    private void initButton() {
        //点击保存按钮
        saveJFXButton.setOnAction(event -> {
            submitData();
        });
    }

    /**
     * 保存，提交数据
     */
    private void submitData() {
        if(Constants.loginUser==null) {
            MyAlert.showError("错误","用户没有登录", "请先登录系统");
            return;//没有登录
        }

        WWeighTemp weighTemp = new WWeighTemp();
        weighTemp.setWeighmanId(Constants.loginUser.getUserId());
        weighTemp.setWeighmanName(Constants.loginUser.getFullname()==null?Constants.loginUser.getUsername():Constants.loginUser.getFullname());

        WLicensePlate licensePlate = lprComboBox.getValue();
        if(licensePlate==null || StringUtils.isEmpty(licensePlate.getWlpNumber())) {
            MyAlert.showError("错误","车牌号有误", "请先填写车牌号");
            lprComboBox.requestFocus();
            return;
        }
        weighTemp.setLicensePlate(licensePlate.getWlpNumber());//车牌号

        String grossWeightStr = grossWeightTextField.getText();
        if(StringUtils.isEmpty(grossWeightStr) || !StringUtil.isPositiveNumber(grossWeightStr)) {
            MyAlert.showError("错误","毛重有误", "请先填写毛重");
            grossWeightTextField.requestFocus();
            return;
        }
        weighTemp.setGrossWeight(Double.parseDouble(grossWeightStr));

        String tareWeightStr = tareWeightTextField.getText();
        if(StringUtils.isEmpty(tareWeightStr) || !StringUtil.isPositiveNumber(tareWeightStr)) {
            MyAlert.showError("错误","皮重有误", "请先填写皮重");
            tareWeightTextField.requestFocus();
            return;
        }
        weighTemp.setTareWeight(Double.parseDouble(tareWeightStr));

        double impurityWeight = 0;
        String impurityWeightStr = impurityWeightTextField.getText();
        if(StringUtils.isNotEmpty(impurityWeightStr) && StringUtil.isPositiveNumber(impurityWeightStr))
            impurityWeight = Double.parseDouble(impurityWeightStr);
        weighTemp.setImpurityWeight(impurityWeight);

        String netWeightStr = netWeightTextField.getText();
        if(StringUtils.isEmpty(netWeightStr) || !StringUtil.isPositiveNumber(netWeightStr)) {
            MyAlert.showError("错误","净重有误", "请先填写净重");
            netWeightTextField.requestFocus();
            return;
        }
        weighTemp.setNetWeight(Double.parseDouble(netWeightStr));

        EWarehouse warehouse = warehouseComboBox.getValue();
        weighTemp.setWarehouseId(warehouse.getWarehouseId());
        weighTemp.setWarehouseName(warehouse.getWarehouseName());

        WCustomer customer = customerComboBox.getValue();

        EGoods goods = goodsComboBox.getValue();
        weighTemp.setGoodsId(goods.getGoodsId());
        weighTemp.setGoodsName(goods.getGoodsName());

        SysUser chargeMan = chargemanComboBox.getValue();
        if(StringUtils.isNotEmpty(chargeMan.getUserId())) {
            weighTemp.setChargemanId(chargeMan.getUserId());
            weighTemp.setChargemanName(chargeMan.getFullname() == null ? chargeMan.getUsername() : chargeMan.getFullname());
        }

        String priceStr = priceTextField.getText();
        if(StringUtils.isNotEmpty(priceStr) && StringUtil.isPositiveNumber(priceStr))
            weighTemp.setPrice(Double.parseDouble(priceStr));

        String deductionMoneyStr = deductionMoneyTextField.getText();
        if(StringUtils.isNotEmpty(deductionMoneyStr) && StringUtil.isPositiveNumber(deductionMoneyStr))
            weighTemp.setDeductionMoney(Double.parseDouble(deductionMoneyStr));

        String amountStr = amountTextField.getText();
        if(StringUtils.isNotEmpty(amountStr))
            if(StringUtil.isPositiveNumber(amountStr))
                weighTemp.setAmount(Double.parseDouble(amountStr));
        weighTemp.setRemark(remarkTextField.getText());

        //获取过磅类别
        WeighTypeBean weighTypeBean = weighTypeComboBox.getSelectionModel().getSelectedItem();
        weighTemp.setWeighType(weighTypeBean.getWeighTypeId());

        if(weighTypeBean.getWeighTypeId()<2){//入库 / 出库
            weighTemp.setIsDelivery(isDeliveryComboBox.getValue().isDelivery());
            SysUser salesMan = salesmanComboBox.getValue();
            if(StringUtils.isNotEmpty(salesMan.getUserId())) {
                weighTemp.setSalesmanId(salesMan.getUserId());
                weighTemp.setSalesmanName(salesMan.getFullname() == null ? salesMan.getUsername() : salesMan.getFullname());
            }
        }

        if(weighTypeBean.getWeighTypeId()==2){//内部周转
            EWarehouse warehouse1 = warehouse1ComboBox.getValue();//原仓库
            weighTemp.setWarehouse1Id(warehouse1.getWarehouseId());
            weighTemp.setWarehouse1Name(warehouse1.getWarehouseName());

            EGoods goods1 = goods1ComboBox.getValue();//原物品
            weighTemp.setGoods1Id(goods1.getGoodsId());
            weighTemp.setGoods1Name(goods1.getGoodsName());
        }else if(customer!=null){//不是内部周转
            weighTemp.setCustomerId(customer.getCustomerId());
            weighTemp.setCustomerName(customer.getCustomerName());
            weighTemp.setCustomerPhone(customer.getCustomerPhone());
        }

        if(enterTimeDateTimePicker.isVoid()){
            MyAlert.showError("错误","进厂日期有误", "请先填写进厂日期");
            enterTimeDateTimePicker.requestFocus();
            return;
        }
        weighTemp.setEnterTime(DateUtil.localDateTime2Date(enterTimeDateTime.get()));

        if(outTimeDateTimePicker.isVoid()){
            MyAlert.showError("错误","出厂日期有误", "请先填写出厂日期");
            outTimeDateTimePicker.requestFocus();
            return;
        }
        weighTemp.setOutTime(DateUtil.localDateTime2Date(outTimeDateTime.get()));

        Date now = new Date();
        weighTemp.setModifyTime(now);
        weighTemp.setCreateTime(now);
        weighTemp.setStatus(0);//过磅完成
        wWeighTempDao.update(weighTemp);

        final boolean isPrint = isPrintJFXToggleButton.isSelected();
        //过磅完成上传到服务器
        switch (weighTemp.getWeighType()){
            case 0://入库
                AppRequest.getInstance().getService().saveRecord(WeighTemp2Entity.weighTemp2EBuy(weighTemp, true))
                        .compose(ServiceRxSchedulers.compose())
                        .subscribe(new ServiceSubscriber<>("保存采购记录") {
                            @Override
                            protected void onHandleSuccess(EBuy eBuy) {
                                submitWeighSuccess(weighTemp, eBuy.getBuyId());
                                if(isPrint)new Thread(new PrintWeighRecordThread(eBuy)).start();//打印
                            }
                        });
                break;
            case 1://出库
                AppRequest.getInstance().getService().saveRecord(WeighTemp2Entity.weighTemp2ESell(weighTemp, true))
                        .compose(ServiceRxSchedulers.compose())
                        .subscribe(new ServiceSubscriber<>("保存销售记录") {
                            @Override
                            protected void onHandleSuccess(ESell eSell) {
                                submitWeighSuccess(weighTemp, eSell.getSellId());
                                if(isPrint)new Thread(new PrintWeighRecordThread(eSell)).start();//打印
                            }
                        });
                break;
            case 2://内部周转
                AppRequest.getInstance().getService().saveRecord(WeighTemp2Entity.weighTemp2ETransfer(weighTemp, true))
                        .compose(ServiceRxSchedulers.compose())
                        .subscribe(new ServiceSubscriber<>("保存内部转库记录") {
                            @Override
                            protected void onHandleSuccess(ETransfer eTransfer) {
                                submitWeighSuccess(weighTemp, eTransfer.getTransferId());
                                if(isPrint)new Thread(new PrintWeighRecordThread(eTransfer)).start();//打印
                            }
                        });
                break;
            case 3://其它过磅
                AppRequest.getInstance().getService().saveRecord(WeighTemp2Entity.weighTemp2EOther(weighTemp, true))
                        .compose(ServiceRxSchedulers.compose())
                        .subscribe(new ServiceSubscriber<>("保存其它过磅记录") {
                            @Override
                            protected void onHandleSuccess(EOther eOther) {
                                submitWeighSuccess(weighTemp, eOther.getOtherWeighId());
                                if(isPrint)new Thread(new PrintWeighRecordThread(eOther)).start();//打印
                            }
                        });
                break;
        }
    }

    /**
     * 上传记录成功后，修改本地临时记录，上传图片
     * @param weighId 服务器返回记录的ID，不是本地临时记录的ID
     */
    private void submitWeighSuccess(WWeighTemp weighTemp, String weighId) {
        weighTemp.setStatus(1);//上传记录成功
        weighTemp.setModifyTime(new Date());
        wWeighTempDao.update(weighTemp);

        clearForm();//保存成功清空表单

        wWeighTempDao.deleteById(weighTemp.getWeighId());
    }

    /**
     * 清空表单
     */
    private void clearForm(){
        lprComboBox.setValue(null);
        grossWeightTextField.setText(null);
        tareWeightTextField.setText(null);
        netWeightTextField.setText(null);
        amountTextField.setText(null);

        impurityWeightTextField.setText(null);
        priceTextField.setText(null);
        deductionMoneyTextField.setText(null);
        remarkTextField.setText(null);
    }

    @Override
    public void close() {

    }

}
